package cn.org.july.weixin.common.bean;

import lombok.Getter;
import lombok.ToString;
import org.apache.commons.codec.digest.DigestUtils;

import java.io.Serializable;
import java.util.Arrays;
import java.util.Objects;

/**
 * 微信接入验证请求参数
 *
 * @auther: wanghongjie
 * @blame: wanghongjie
 * @date: 2020-08-29 10:17
 * @Description:
 */
@Getter
@ToString
public class AccessAuthenticationBean implements Serializable {
    /**
     * 微信加密签名，signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
     */
    private final String signature;
    /**
     * 时间戳
     */
    private final String timestamp;
    /**
     * 随机数
     */
    private final String nonce;
    /**
     * 随机字符串
     */
    private final String echoStr;

    private AccessAuthenticationBean(String signature, String timestamp, String nonce, String echoStr) {
        this.signature = signature;
        this.timestamp = timestamp;
        this.nonce = nonce;
        this.echoStr = echoStr;
    }

    public static AccessAuthenticationBean of(String signature, String timestamp, String nonce, String echoStr) {
        return new AccessAuthenticationBean(signature, timestamp, nonce, echoStr);
    }

    /**
     * 参数验证龙锦苑东五区21号楼五单元201
     *
     * @return 验证结果
     */
    public boolean check(String token) {
        //1、排序
        String[] strSort = new String[]{token, this.timestamp, this.nonce};
        Arrays.sort(strSort);
        //2、字符串合并
        String str = strSort[0] + strSort[1] + strSort[2];
        String sha1 = sha1(str);
        return Objects.requireNonNull(sha1).equalsIgnoreCase(this.signature);
    }

    private String sha1(String source) {
        return DigestUtils.sha1Hex(source);
    }

}
